const gulp = require('gulp');
const connect = require('gulp-connect');
const babel = require('gulp-babel');
const less = require('gulp-less');
const postcss = require('gulp-postcss');
const del = require('del');
const log4js = require('log4js');
const autoprefixer = require('autoprefixer');
const logger = log4js.getLogger();
const proxy = require('http-proxy-middleware');
logger.level = 'debug';

gulp.task('build:es', reslove => {
  gulp
    .src('src/**/*.js')
    .pipe(babel())
    .pipe(gulp.dest('lib'))
    .on('end', () => {
      reslove();
    });
});

gulp.task('build:del', reslove => {
  del([
    'lib/**/*'
  ]).then(() => {
    reslove();
  });
})

gulp.task('build:style', function (reslove) {
  // 处理less css 文件
  const postcssPlugin = [
    require('postcss-flexbugs-fixes'),
    autoprefixer({
      browsers: ['> 1%', 'last 3 versions', 'Firefox >= 20', 'iOS >=7'],
      // flexbox: 'no-2009',
      flexbox: true
    }),
  ];
  gulp
    .src([
      'src/**/*.less',
      'src/**/*.css',
      // ignore
      '!src/**/_*.less',
    ])
    .pipe(less())
    .pipe(postcss(postcssPlugin))
    .pipe(gulp.dest('lib'))
    .on('end', function () {
      reslove();
    });
});

gulp.task('build:html', reslove => {
  gulp
    .src(['src/**/*.html', 'src/**/*.htm'])
    .pipe(gulp.dest('lib'))
    .on('end', () => reslove());
});

gulp.task('build', gulp.series([
  'build:del',
  'build:es',
  'build:html',
  'build:style'
]));

gulp.task('dev:reload', function (reslove) {
  gulp.src('lib/**/*.html')//指定被刷新的html路径
    .pipe(connect.reload())
    .on('end', () => {
      reslove();
    });
});

gulp.task('dev:connect', function (reslove) {
  connect.server({
    livereload: true,
    port: 8080,
    middleware: function (connect, opt) {
      return [
        proxy('/v1', {
          target: 'http://127.0.0.1:7001',
          changeOrigin: true
        }),
      ]
    }
  });
  reslove();
});

gulp.task('dev:watch', function (reslove) {
  gulp
    .watch([
      'src/**/*',
    ], gulp.series(['build', 'dev:reload']))
    .on('end', () => {
      reslove();
    });
});

gulp.task('dev', gulp.series(['dev:connect', 'dev:reload', 'dev:watch']));
